<script setup lang="ts">
import {computed, onMounted, ref} from "vue";
import type TagProp from "@/components/tag/type/TagProp.ts";
import {mixHexWithWhite} from "@/components/utils.ts";
import {copyToClipboard} from "@/components/strs.ts";
import type TagEmit from "@/components/tag/type/TagEmit.ts";

const $emit = defineEmits<TagEmit>()

const $prop = withDefaults(defineProps<TagProp>(), {
  type: 'primary'
})

/**
 * 颜色配置
 */
const colorMap = {
  primary: '--primary-color',
  success: '--success-color',
  warning: '--warning-color',
  danger: '--danger-color',
  info: '--info-color',
}

/**
 * 获取 CSS 变量值
 */
const cssVariableCache = new Map<string, string>()
const getCSSVariable = (variable: string): string => {
  if (!cssVariableCache.has(variable)) {
    const value = getComputedStyle(document.documentElement)
        .getPropertyValue(variable)
        .trim()
    cssVariableCache.set(variable, value)
  }
  return cssVariableCache.get(variable)!
}

//当前应该使用的颜色
const currentColor = computed(() => {
  return $prop.color ?? getCSSVariable(colorMap[$prop.type!])
})

const tagCode = computed(() => {
  return $prop.code ?? $prop.label
})

const textColor = ref('')
const backgroundColor = ref('')
const borderColor = ref('')

onMounted(() => {
  const themeColor = currentColor.value

  textColor.value = themeColor
  backgroundColor.value = mixHexWithWhite(themeColor, 0.9)
  borderColor.value = mixHexWithWhite(themeColor, 0.8)
})

</script>

<template>
  <div class="tag-container" @click.stop>
    <template v-if="icon">
      <component :is="icon" class="tag-icon"/>
    </template>

    <div class="tag-body" @dblclick="copyToClipboard(label)">
      {{ label }}
    </div>

    <template v-if="closeable">
      <component is="close" class="close" @click="() => $emit('close', tagCode)"/>
    </template>
  </div>
</template>

<style scoped>
.tag-container {
  min-height: 25px;
  color: v-bind(textColor);
  background-color: v-bind(backgroundColor);
  border: 1px solid v-bind(borderColor);
  border-radius: 1px;
  padding: 0 4px;
  gap: 3px;
  font-size: inherit;

  display: inline-flex;
  justify-content: space-between;
  align-items: center;
}

.tag-body {
  white-space: nowrap;
  overflow: hidden;      /* 可选：防止内容溢出时撑破容器 */
  text-overflow: ellipsis; /* 可选：溢出时显示省略号 */
}

.close {
  cursor: pointer;
  transition: background-color 300ms ease;
}

.close:hover {
  background-color: v-bind(borderColor);
}

</style>